package com.cosytek.farmmanager;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.cosytek.farmmanager.data.Farm;
import com.cosytek.farmmanager.data.Main;
import com.cosytek.farmmanager.data.Task;
import com.cosytek.farmmanager.data.TaskSummary;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FarmFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FarmFragment extends Fragment implements AdapterView.OnItemClickListener, ServerRequest.IServerRequestListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "farmId";
    private static final String PATH_LOAD_TASK = "/loadTask";

    // TODO: Rename and change types of parameters
    private String farmId;

    private OnFragmentInteractionListener mListener;
    private View mProgressForm;
    private Activity parent;
    private ListView viewTaskList;
    private View viewNoTaskText;

    private FarmFragmentTaskAdapter taskAdapter;
    private LayoutInflater layoutInflater;

    private TextView viewFarmName;
    private TextView viewFarmDescription;
    private TextView viewFarmTaskCount;
    private TextView viewFarmPlanCount;
    private TextView viewFarmSensorCount;
    private TextView viewFarmExecutorCount;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment FarmFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FarmFragment newInstance(String param1) {
        FarmFragment fragment = new FarmFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    public FarmFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            farmId = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        layoutInflater = inflater;
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_farm, container, false);
        mProgressForm = view.findViewById(R.id.common_progress_form);
        viewTaskList = (ListView)view.findViewById(R.id.frag_farm_task_list);
        viewNoTaskText = view.findViewById(R.id.frag_farm_task_list_no_task);

        viewFarmName = (TextView)view.findViewById(R.id.frag_farm_name);
        viewFarmDescription = (TextView)view.findViewById(R.id.frag_farm_description);
        viewFarmTaskCount = (TextView)view.findViewById(R.id.frag_farm_task_count);
        viewFarmPlanCount = (TextView)view.findViewById(R.id.frag_farm_plan_count);
        viewFarmSensorCount = (TextView)view.findViewById(R.id.frag_farm_executor_count);
        viewFarmExecutorCount = (TextView)view.findViewById(R.id.frag_farm_sensor_count);

        viewTaskList.setOnItemClickListener(this);

        refreshUI();
        return view;
    }

    private void refreshUI() {
        MainActivity ma = (MainActivity)parent;
        Main main = ma.getMain();

        Farm f = main.getFarm(farmId);
        if (f == null) {
            return;
        }

        viewFarmName.setText(f.getName());
        viewFarmDescription.setText(f.getDescription());
        viewFarmTaskCount.setText(String.format("%d", f.getTaskCount()));
        viewFarmPlanCount.setText(String.format("%d", f.getPlanCount()));
        viewFarmSensorCount.setText(String.format("%d", f.getSensorCount()));
        viewFarmExecutorCount.setText(String.format("%d", f.getExecutorCount()));

        if (taskAdapter == null) {
            taskAdapter = new FarmFragmentTaskAdapter(ma.getMain(), farmId, layoutInflater);
            viewTaskList.setAdapter(taskAdapter);
        } else {
            taskAdapter.updateData(ma.getMain(), farmId);
        }

        if (f.getTaskCount() > 0) {
            viewNoTaskText.setVisibility(View.GONE);
            viewTaskList.setVisibility(View.VISIBLE);
        } else {
            viewNoTaskText.setVisibility(View.VISIBLE);
            viewTaskList.setVisibility(View.GONE);
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(this, uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
            parent = activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        parent = null;
        layoutInflater = null;
    }

    public void updateFarm(String farmId) {
        this.farmId = farmId;

        refreshUI();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        MainActivity ma = (MainActivity)this.parent;
        Main m = ma.getMain();
        if (m == null) {
            return;
        }

        Farm f = m.getFarm(farmId);
        if (f == null) {
            return;
        }

        TaskSummary ts = f.getTaskSummary(position);
        String taskId = ts.getId();
        Task t = f.getTaskById(taskId);

        if (t == null || t.isDataExpired()) {
            loadTask(taskId);
        } else {
            showTaskFragment(taskId);
        }
    }

    private void showTaskFragment(String taskId) {
        MainActivity ma = (MainActivity)this.parent;
        ma.showTaskFragment(farmId, taskId);
    }

    private void loadTask(String taskId) {
        mProgressForm.setVisibility(View.VISIBLE);

        String token = ((MainActivity)parent).getToken();
        ServerRequest request = ServerRequest.newGetRequest(this, token, String.format("%s?fid=%s&tid=%s",PATH_LOAD_TASK, farmId, taskId));
        request.setTag("task");
        request.execute();
    }

    @Override
    public void onRequestCompleted(ServerRequest r, boolean success, ServerError error, String respBody) {
        mProgressForm.setVisibility(View.GONE);

        if (parent == null) {
            return;
        }

        if (success) {
            String tag = r.tag();
            switch (tag) {
                case "task":
                    MainActivity ma = (MainActivity)this.parent;
                    Main m = ma.getMain();
                    Farm f = m.getFarm(farmId);
                    if (f == null) {
                        return;
                    }

                    Task t = f.onTaskLoaded(respBody);
                    if (t == null) {
                        return;
                    }

                    showTaskFragment(t.getId());
                    break;
            }

            return;
        }

        if (error != null) {
            UIHelper.promptError(parent, error);
        }
    }
}
